package masterjava.common.dao.hibernate;

import masterjava.common.dao.DaoContext;
import masterjava.common.logging.ServerLogger;
import masterjava.common.shared.FetchContext;
import org.hibernate.Criteria;
import org.hibernate.Query;

/**
 * User: Grigory Kislin
 * Date: 04/07/11
 */
public class FetchDaoContext implements DaoContext {

    private static final ServerLogger LOGGER = ServerLogger.get(FetchDaoContext.class);

    private final FetchContext ctx;

    public FetchDaoContext(FetchContext ctx) {
        this.ctx = ctx;
    }

    @Override
    public Criteria prepareCriteria(Criteria c) {
        if (ctx != null) {
            LOGGER.debug("prepareCriteria " + ctx.toString());
            c.setCacheable(ctx.isCacheQueries());

            int firstResult = ctx.getFirstResult();
            if (firstResult != 0) {
                c.setFirstResult(firstResult);
            }
            int maxResults = ctx.getMaxResults();
            if (maxResults != 0) {
                c.setMaxResults(maxResults);
            }
        }
        return c;
    }

    @Override
    public Query prepareQuery(Query q) {
        if (ctx != null) {
            LOGGER.debug("prepareQuery " + ctx.toString());
            q.setCacheable(ctx.isCacheQueries());

            int firstResult = ctx.getFirstResult();
            if (firstResult != 0) {
                q.setFirstResult(firstResult);
            }
            int maxResults = ctx.getMaxResults();
            if (maxResults != 0) {
                q.setMaxResults(maxResults);
            }
        }
        return q;
    }
}
